package com.dataStructures.hashtab;

import java.util.Scanner;

/**
 * 哈希表
 */
public class HashTabDemo {
	public static void main(String[] args) {
		HashTab hashTab = new HashTab(7);
		String key = "";
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.println("add: 添加雇员");
			System.out.println("list: 显示雇员");
			System.out.println("find: 查找雇员");
			System.out.println("exit: 退出系统");
			key = scanner.next();
			switch (key) {
				case "add":
					System.out.println("输入 id");
					int id = scanner.nextInt();
					System.out.println("输入名字");
					String name = scanner.next(); //创建 雇员
					Emp emp = new Emp(id, name);
					hashTab.add(emp);
					break;
				case "list":
					hashTab.list();
					break;
				case "find":
					System.out.println("请输入要查找的 id");
					id = scanner.nextInt();
					hashTab.findById(id);
					break;
				case "exit":
					scanner.close();
					System.exit(0);
				default:
					break;
			}
		}
	}
}

class HashTab {
	private EmpLinkedList[] list;
	private int size;

	public HashTab(int size) {
		this.list = new EmpLinkedList[size];
		this.size = size;
		for (int i = 0; i < size; i++) {
			list[i] = new EmpLinkedList();
		}
	}

	private int hashFun(int id) {
		return id % size;
	}

	public void add(Emp emp) {
		int no = hashFun(emp.id);
		list[no].add(emp);
	}

	public void list() {
		for (int i = 0; i < size; i++) {
			list[i].list(i);
		}
	}

	public void findById(int id) {
		int no = hashFun(id);
		Emp emp = list[no].findEmpById(id);
		if (emp != null) {
			System.out.printf("在第%d 条链表中找到 雇员 id = %d\n", (no + 1), id);
		} else {
			System.out.println("在哈希表中，没有找到该雇员~");
		}
	}
}

/**
 * 雇员信息
 */
class Emp {
	public int id;
	public String name;
	public Emp next;

	public Emp(final int id, final String name) {
		this.id = id;
		this.name = name;
	}
}

/**
 * 雇员链表
 */
class EmpLinkedList {
	private Emp head;

	/**
	 * 添加雇员
	 */
	public void add(Emp emp) {
		if (head == null) {
			head = emp;
			return;
		}

		Emp temp = head;
		while (temp.next != null) {
			temp = temp.next;
		}
		temp.next = emp;
	}

	/**
	 * 遍历
	 */
	public void list(int no) {
		if (head == null) {
			System.out.println("Num " + no + " is empty");
			return;
		}
		System.out.println("Num " + no + " info: ");
		Emp temp = head;
		while (true) {
			System.out.printf("→ id=%d name=%s\t", temp.id, temp.name);
			if (temp.next == null) {
				break;
			}
			temp = temp.next;
		}
		System.out.println();
	}

	/**
	 * 查找
	 */
	public Emp findEmpById(int id) {
		if (head == null) {
			System.out.println("list empty");
			return null;
		}
		Emp temp = head;
		while (true) {
			if (temp.id == id) {
				return temp;
			}
			if (temp.next == null) {
				return null;
			}
			temp = temp.next;
		}
	}
}